package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.common.result.Result;
import com.example.entity.auth.SysMenu;
import com.example.entity.dto.User.DscmaListDto;
import com.example.entity.dto.User.MyUser;
import com.example.entity.dto.User.UserLoginDto;
import com.example.entity.hz.Zdy;
import com.example.entity.vo.CMSMFVo;
import com.example.entity.vo.User.DscmaVo;
import com.example.entity.vo.User.UserLoginVo;
import com.example.entity.yifei.Cmsme;
import com.example.entity.yifei.Dscma;
import com.example.mapper.CmsmeMapper;
import com.example.mapper.DscmaMapper;
import com.example.mapper.UserMapper;
import com.example.mapper.ZdyMapper;
import com.example.service.UserService;
import com.example.service.auth.SysMenuService;
import com.example.untils.JwtUtil;
import com.example.untils.JwtUtils;
import com.example.untils.SecurityUtils;
import com.example.untils.StringUtils;
import com.github.houbb.heaven.util.lang.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private DscmaMapper dscmaMapper;

    @Autowired
    private UserMapper userMapper;
    @Resource
    private ZdyMapper zdyMapper;
    @Autowired
    private SysMenuService sysMenuService;
    @Resource
    private AuthenticationManager authenticationManager;
    @Autowired
    private CmsmeMapper cmsmeMapper;

    @Override
    public Result queryList(String name) {

        List<Cmsme> cmsmeList = cmsmeMapper.selectList(null);
        Map<String, String> cmsmeMap = new HashMap<>();
        for(Cmsme t : cmsmeList) cmsmeMap.put(t.getMe001().trim(), t.getMe002().trim());

        QueryWrapper<Dscma> dscmaQueryWrapper =new QueryWrapper<>();
//        dscmaQueryWrapper.eq("COMPANY", YmlConfig.getYFCOMPANY());
        if (StringUtils.isNotEmpty(name)){
            dscmaQueryWrapper.like("MA001",name).or().like("MA002",name);
        }
        List<Dscma> dscmas = this.dscmaMapper.selectList(dscmaQueryWrapper);
        for(Dscma t : dscmas) {
            if(StringUtils.isNotEmpty(t.getUdf01())) t.setDeptName(cmsmeMap.get(t.getUdf01().trim()));
        }
        return Result.success(dscmas);
    }

    @Override
    public Result<UserLoginVo> userLogin(UserLoginDto userLoginDto,
                                         HttpServletRequest request) {

        if(StringUtils.isEmpty(userLoginDto.getUserId())) {
            return Result.error("用户名不能为空", "500");
        }
//        if(StringUtils.isEmpty(userLoginDto.getPassword())) {
//            return Result.error("密码不能为空", "500");
//        }
//        if(StringUtils.isEmpty(userLoginDto.getCompany())) {
//            return Result.error("账套不能为空", "401");
//        }
        Integer integer = userMapper.userLogin(userLoginDto);
        if(integer == null || integer == 0) {
            return Result.error("用户名或者密码错误", "500");
        }
//创建一个 UsernamePasswordAuthenticationToken 对象，用于存储用户名和密码。
        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(userLoginDto.getUserId(), userLoginDto.getPassword());
        // AuthenticationContextHolder.setContext(authenticationToken);
        // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
//        使用 authenticationManager 来认证用户，并将认证结果存储在 SecurityContextHolder 中。
        Authentication authentication = authenticationManager.authenticate(authenticationToken);

        SecurityContextHolder.getContext().setAuthentication(authentication);

        QueryWrapper<Dscma> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("MA001", userLoginDto.getUserId());

        Dscma dscma = dscmaMapper.selectOne(queryWrapper);
//        request.getSession().setAttribute("userLogin", dscma);
//        return new UserLoginVo("登录成功");

        MyUser myUser = SecurityUtils.getLoginUser();

        Integer integer1 = this.userMapper.getma068();
        List<CMSMFVo> getcmsmf = this.userMapper.getcmsmf();

        Integer i = this.userMapper.querySg(dscma.getMa001());

        Zdy zdy = this.zdyMapper.selectOne(new LambdaQueryWrapper<Zdy>().eq(Zdy::getCode, dscma.getMa001()));

        List<SysMenu> menulist = sysMenuService.findMenuByRoleId(1L);

        return Result.success(new UserLoginVo(menulist, JwtUtils.getJwtToken(new DscmaVo(dscma.getMa001(), dscma.getMa002())),
                dscma.getMa001(), dscma.getMa002(), myUser.getYfPermission(),myUser.getMesPermission(), integer1,getcmsmf, zdy == null ? null : zdy.getContent(),i));
//        return Result.success(new UserLoginVo(JwtUtils.getJwtToken(userLoginDto.getUserId())));
    }

    @Override
    public List<Dscma> dscmaList(DscmaListDto dto) {
        return dscmaMapper.dscmaList(dto);
    }

    @Override
    public Result selectlogin(UserLoginDto userLoginDto) {
        String password=dscmaMapper.selectpassword(userLoginDto);
        if (password==null){
            return Result.fail("密码错误！");
        } else if (userLoginDto.getPassword().equals("000") && StringUtil.isBlank(password)) {
            QueryWrapper<Dscma> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("MA001", userLoginDto.getUserId());
            Dscma dscma = dscmaMapper.selectOne(queryWrapper);
            List<SysMenu> menulist = new ArrayList<>();
            return Result.success(new UserLoginVo(menulist,"123456",null,null,null,null,null,null,null,null));
        } else if (password.equals(userLoginDto.getPassword())){
            QueryWrapper<Dscma> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("MA001", userLoginDto.getUserId());
            Dscma dscma = dscmaMapper.selectOne(queryWrapper);
            List<SysMenu> menulist = new ArrayList<>();
            return Result.success(new UserLoginVo(menulist,"123456",null,null,null,null,null,null,null,null));
        }else {
            return Result.fail();
        }
    }
    }

    // 用户注销
//    @Override
//    public boolean userLogout(HttpServletRequest request) {
//        if (request.getSession().getAttribute("userLogin") == null) {
//            return false;
//        }
//        // 移除登录态
//        request.getSession().removeAttribute("userLogin");
//        return true;
//    }

